package com.yjt.admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjt.admin.system.dao.SystemFileMapper;
import com.yjt.admin.system.entity.SystemFile;
import com.yjt.admin.system.form.SystemFileForm;
import com.yjt.admin.system.service.SystemFileService;
import com.yjt.admin.system.vo.SystemFileVO;
import com.yjt.common.config.FastDFSClientWrapper;
import com.yjt.common.utils.ComUtil;
import com.yjt.common.utils.SecurityUtils;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 系统文件表 服务实现类
 * </p>
 *
 * @author zzp
 * @since 2021-10-12
 */
@Service
public class SystemFileServiceImpl extends ServiceImpl<SystemFileMapper, SystemFile> implements SystemFileService {

    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SystemFileVO addOneFile(MultipartFile file, SystemFileForm systemFileForm) {
        //先删除以前的文件
        if (ComUtil.isNotNullStr(systemFileForm.getActId())) {
            LambdaUpdateWrapper lambdaUpdateWrapper = Wrappers.<SystemFile>lambdaUpdate().eq(SystemFile::getActId, systemFileForm.getActId());
            this.remove(lambdaUpdateWrapper);
        }
        //获取文件信息
        byte[] bytes = file.getBytes();
        String originalFileName = file.getOriginalFilename();
        String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        long fileSize = file.getSize();
        String fileUrl = fastDFSClientWrapper.uploadFile(bytes, fileSize, extension);

        //构造参数保存
        SystemFile systemFilePo = new SystemFile();
        BeanUtils.copyProperties(systemFileForm, systemFilePo);
        systemFilePo.setFileUrl(fileUrl);
        systemFilePo.setFileName(originalFileName);
        systemFilePo.setCreateBy(SecurityUtils.getUserId());
        this.save(systemFilePo);

        //构造返回数据
        SystemFileVO systemFileVO = new SystemFileVO();
        BeanUtils.copyProperties(systemFilePo, systemFileVO);

        return systemFileVO;
    }

    @Override
    public void updateOneFile(SystemFileForm systemFileForm) {
        if (ComUtil.isNotNullStr(systemFileForm.getFileId())) {
            //只有当文件id不为空的时候才更新
            SystemFile systemFilePo = new SystemFile();
            BeanUtils.copyProperties(systemFileForm, systemFilePo);
            this.updateById(systemFilePo);
        }
    }
}
